package com.logicbus.redis.xscript;

import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.alogic.xscript.plugins.Segment;
import com.anysoft.util.IOTools;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import com.logicbus.redis.client.Client;

/**
 * 开启Redis客户端
 *
 * @since 1.6.12.56 [20191226] <br>
 */
public class RedisClient extends Segment {
    protected static final String DEFAULT_IP = "127.0.0.1";
    protected static final int DEFAULT_PORT = 6379;
    protected static final int DEFAULT_DB = 0;

    protected String $ip;
    protected String $port;
    protected String $db;
    protected String $password;
    protected String cid = "$redis-client";

    public RedisClient(String tag, Logiclet p) {
        super(tag, p);

        registerModule("redis-info",RedisInfo.class);
        registerModule("redis-info-scan",RedisInfoScan.class);
    }

    @Override
    public void configure(Properties p){
        super.configure(p);

        cid = PropertiesConstants.getString(p,"cid",cid);
        $ip = PropertiesConstants.getRaw(p,"ip",$ip);
        $port = PropertiesConstants.getRaw(p,"port",$port);
        $db = PropertiesConstants.getRaw(p,"db",$db);
        $password = PropertiesConstants.getRaw(p,"password",$password);
    }

    protected void onExecute(XsObject root, XsObject current, LogicletContext ctx, ExecuteWatcher watcher) {
        String ip = PropertiesConstants.transform(ctx,$ip,DEFAULT_IP);
        int port = PropertiesConstants.transform(ctx,$port,DEFAULT_PORT);
        int db = PropertiesConstants.transform(ctx,$db,DEFAULT_DB);
        String pwd = PropertiesConstants.transform(ctx,$password,"");

        Client client = null;
        try {
            client = new Client(ip,port,pwd,db);
            client.connect();
            ctx.setObject(cid,client);
            super.onExecute(root,current,ctx,watcher);
        }finally{
            ctx.removeObject(cid);
            IOTools.close(client);
        }
    }
}
